package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.mapper.RoleMapper;
import com.ruoyi.system.mapper.RoleMenuMapper;
import com.ruoyi.system.mapper.SysRoleMenuMapper;
import com.ruoyi.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, SysRole> implements IRoleService {
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveAll(SysRole role) {
        int i = baseMapper.insert(role);
        if(i>0){
            Long[] menuIds = role.getMenuIds();
            List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
            if(StringUtils.isNotEmpty(menuIds)){
                for (Long menuId : menuIds) {
                    SysRoleMenu rm = new SysRoleMenu();
                    rm.setRoleId(role.getRoleId());
                    rm.setMenuId(menuId);
                    list.add(rm);
                }
            }
            roleMenuMapper.batchRoleMenu(list);
        }
        return i;
    }

    @Override
    public List<Long> selectRoleListByUserId(Long userId) {
        return baseMapper.selectRoleListByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRole(SysRole role) {
        // 修改角色信息
        int i = baseMapper.updateById(role);
        if(i>0){
            // 删除角色与菜单关联
            LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysRoleMenu::getRoleId,role.getRoleId());
            roleMenuMapper.delete(wrapper);
            Long[] menuIds = role.getMenuIds();
            List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
            if(StringUtils.isNotEmpty(menuIds)){
                for (Long menuId : menuIds) {
                    SysRoleMenu rm = new SysRoleMenu();
                    rm.setRoleId(role.getRoleId());
                    rm.setMenuId(menuId);
                    list.add(rm);
                }
            }
            roleMenuMapper.batchRoleMenu(list);
        }
        return i;
    }


}
